/**
 * 定义全局函数与全局配置
 */
!function (factory) {
    "use strict";
    'function' === typeof define && define.amd ? define(['jquery', 'gritter', 'layer', 'const'], factory) : factory(jQuery)
}(function ($) {

    /**
     * 自动将form表单封装成json对象
     */
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "H+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    var action302 = function (xhr) {
        var responseText = JSON.parse(xhr.responseText);
        // 登录失效，跳转到登录界面
        if (responseText.hasOwnProperty('code')
            && parseInt(responseText.code) === $.Const.LOGIN_INVALID) {

            $.xumf.openLoginFrame();
            // layer.open({
            //     title: '登录超时',
            //     maxmin: false,
            //     shadeClose: false,
            //     area: ['450px', '110px'],
            //     btn: null,
            //     content: '<form method="post" action="/login/action" style="padding: 12px;" class="form-inline">\
            //                         <input name="loginName" type="text" class="input-normal" placeholder="账号">\
            //                         <input name="password" type="password" class="input-normal" placeholder="密码">\
            //                         <button style="margin-bottom: 4px;" type="button" class="btn btn-info btn-sm">\
            //                             <i class="ace-icon fa fa-key bigger-110"></i>登录\
            //                         </button>\
            //                     </form>',
            //     success: function (layero, index) {
            //         $(layero).find('.btn.btn-info.btn-sm').on('click', function (event) {
            //             var $form = $(event.currentTarget).closest('form');
            //             var $passwordInput = $(event.currentTarget).siblings('input[type=password]');
            //             var password = $passwordInput.val();
            //             // 加密后密码
            //             var encryptPassword = $.xumf.encrypt(password);
            //             $passwordInput.val(encryptPassword);
            //             $form.ajaxSubmit({
            //                 success: function (res) {
            //                     $passwordInput.val('');
            //                     if (res.success) {
            //                         layer.close(index);
            //                     } else {
            //                         $.xumf.gritterError(res.detailMsg);
            //                     }
            //                 },
            //                 error: function (res) {
            //                     $.xumf.gritterError(res.detailMsg);
            //                 }
            //             });
            //             event.preventDefault();
            //         })
            //     }
            // });
        }
    };

    // ajax全局设置
    $.ajaxSetup({
        url: "/", // 默认URL
        async: true, // 默认异步加载
        type: "POST", // 默认使用GET方式
        headers: { "ajax-certification": "yes" }, // 默认添加请求头
        error: function (xhr, textStatus, errorMsg) { // 出错时默认的处理函数
            $.xumf.hideLoading();
            var status = xhr.status;
            if (status === 404) {
                return;
            }
            if (status === 405) {
                $.xumf.gritterError('请求方法错误');
                return;
            }
            var responseText = JSON.parse(xhr.responseText || '{}');
            if (status === 500) {
                $.xumf.gritterError(responseText.detailMsg);
            }
            else if (status === 403) {
                $.xumf.gritterError("没有权限进行操作！");
            }
            else if (status === 401) {
                if (responseText.code === 10003 || responseText.code === 10007) {
                    $.xumf.gritterError(responseText.detailMsg);
                }
            }
            else if (status === 302) {
                action302(xhr);
            }
            /*      if (xhr.status === 404) {
                      layer.alert(
                          '[{{status}}]:{{msg}}'.replace(/{{status}}/, xhr.status).replace(/{{msg}}/, errorMsg)
                      );
                  }*/

        },
        complete: function (xhr, status) {
            var st = xhr.status;
            if (st === 302) {
                action302(xhr);
            }
        }
    });

    // layer 默认配置
    layer.config({
        zIndex: 999,
        btn: ['确定', '取消'],
        closeBtn: 0, //不显示关闭按钮
        shadeClose: true, //开启遮罩关闭
        maxmin: true, // 最大最小化
        type: 1,
        anim: 0, //默认动画风格
        skin: 'layui-layer-lan' //默认皮肤
    });

    $.fn.select2.defaults.set('language', 'zh-CN');
    $.fn.select2.defaults.set("ajax--cache", false);
    $.fn.select2.defaults.set("ajax--delay", 250);

    // tableexport 配置
    // 每种导出类型的默认类，内容和分隔符

    // Excel Open XML电子表格（.xlsx）
    $.fn.tableExport.xlsx = {
        defaultClass: "xlsx",
        buttonContent: "Export to xlsx",
        mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        fileExtension: ".xlsx"
    };

    // Excel二进制电子表格（.xls）
    $.fn.tableExport.xls = {
        defaultClass: "xls",
        buttonContent: "Export to xls",
        separator: "\t",
        mimeType: "application/vnd.ms-excel",
        fileExtension: ".xls"
    };

    // 逗号分隔值（.csv）
    $.fn.tableExport.csv = {
        defaultClass: "csv",
        buttonContent: "Export to csv",
        separator: ",",
        mimeType: "application/csv",
        fileExtension: ".csv"
    };

    // 纯文本（.txt）
    $.fn.tableExport.txt = {
        defaultClass: "txt",
        buttonContent: "Export to txt",
        separator: "  ",
        mimeType: "text/plain",
        fileExtension: ".txt"
    };

    // 默认字符集编码（UTF-8
    $.fn.tableExport.charset = "charset = utf-8";

    // 默认文件名，如果设置了“id”属性并且未定义
    $.fn.tableExport.defaultFileName = "myDownload";

    // 默认类在不使用bootstrap时设置样式按钮
    $.fn.tableExport.defaultButton = "button-default";

    //  bootstrap类用于设置和定位导出按钮
    $.fn.tableExport.bootstrap = ["btn", "btn-default", "btn-toolbar"];

    // 所有文件类型中使用的行分隔符
    $.fn.tableExport.rowDel = "\ r \ n";

    // 验证插件 默认配置
    $.validator.setDefaults({
        errorClass: 'help-block',
        highlight: function (e) {
            $(e).closest('div').addClass('has-error');
        },
        unhighlight: function (e) {
            $(e).closest('div').removeClass('has-error');
        },
        errorElement: "em"
    });

    // 更改Underscore 模块表达式 {{}}表达式来逐字匹配
    _.templateSettings = {
        interpolate: /\{\{(.+?)\}\}/g
    };

    var loadingOfIndex = null;
    $.xumf = {
        // 带有加载的ajax
        ajaxAndLoading: function (opt) {
            var setting = {
                beforeSend: function () {
                    $.xumf.showLoading();
                },
                complete: function () {
                    $.xumf.hideLoading();
                }
            };
            var options = $.extend({}, setting, opt);
            if (opt.hasOwnProperty('beforeSend')) {
                options.beforeSend = function () {
                    setting.beforeSend();
                    options.beforeSend();
                }
            }
            if (opt.hasOwnProperty('complete')) {
                options.complete = function () {
                    setting.complete();
                    options.complete();
                }
            }
            return $.ajax(options);
        },
        /**
         * 广发通登录弹框
         * @param needRedirect 是否不要重定向
         * @constructor
         */
        openLoginFrame: function () {

            var $iframe = $('<iframe></iframe>').css({
                width: '604px',
                height: '400px',
                'margin-top': '136px',
                frameBorder: 0,
                border: '0 solid',
                scrolling: 'no'
            }).attr({
                src: $.Const.GFT_LOGIN_URL
            }).addClass('center-block');
            // 背景蒙层
            var $backgroundDiv = $('<div style="background-color: rgba(0, 0, 0, 0.3)"></div>').css({
                width: '100%',
                height: $(window).height(),
                position: 'absolute',
                top: 0,
                left: 0,
                "z-index": 999999,
                display: 'none'
            }).append($iframe).fadeIn();

            var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
            var eventer = window[eventMethod];
            var messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message";
            eventer(messageEvent, function (e) {
                //TODO: 用户用户名及密码验证通过后，触发跳转应用方的</login/callback>
                window.location = e.data.url;
            }, false);
            $(document.body).append($backgroundDiv);
        },
        alert: function (msg, opt) {
            var options = $.extend({}, {
                maxmin: false,
                btn: ['确定']
            }, opt || {});
            return layer.alert('<div style="padding: 12px;">{{msg}}</div>'.replace(/{{msg}}/, msg), options);
        }

        ,
        confirm: function (msg, opt, confirm, cancel) {
            var options = $.extend({}, {
                maxmin: false,
                btn: ['确定', '取消']
            }, opt || {});
            if ('function' === typeof opt) {
                cancel = confirm;
                confirm = opt;
            }
            return layer.confirm('<div style="padding: 24px;">{{msg}}</div>'.replace(/{{msg}}/, msg), options, confirm, cancel);
        }
        ,
        /**
         * 显示提示框
         * @param message 信息
         * @param success 请求是否成功
         */
        gritter: function (message, success) {
            if ('string' !== typeof message) {
                success = message.success;
                message = message.detailMsg;
            }
            $.gritter.add({
                title: '提示',
                text: message,
                time: success ? $.Const.GRITTER.SUCCESS.TIME : $.Const.GRITTER.ERROR.TIME,
                class_name: 'gritter-' + (success ? $.Const.GRITTER.SUCCESS.MESSAGE : $.Const.GRITTER.ERROR.MESSAGE + ' gritter-light')
            });
        }
        ,
        gritterError: function (message) {
            $.xumf.gritter(message, false);
        }
        ,
        gritterSuccess: function (message) {
            $.xumf.gritter(message, true);
        }
        ,
        // 显示loading
        showLoading: function () {
            loadingOfIndex = layer.load(0, { shade: false, btn: null });
        }
        ,
        // 隐藏loading
        hideLoading: function () {
            loadingOfIndex && layer.close(loadingOfIndex);
        }
        ,

        // 数组方法
        array: {
            // 上移
            moveUp: function (arr, index) {
                if (index >= 1 && arr.length > 1) {
                    arr.splice(index - 1, 2, arr[index], arr[index - 1]);
                }
            }
            ,
            // 下移
            moveDown: function (arr, index) {
                if (index < arr.length - 1 && arr.length > 1) {
                    arr.splice(index, 2, arr[index + 1], arr[index]);
                }
            }
        }
        ,
        getCookie: function (name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg)) {
                return unescape(arr[2]);
            }
            else {
                return null;
            }
        }
        ,
        /**
         * aes 加密
         * @param beforeVal 明文
         * @returns {*|PromiseLike<ArrayBuffer>} 加密后
         */
        encrypt: function (beforeVal) {
            // 密码进行aes加密
            var key = CryptoJS.enc.Utf8.parse($.Const.PASSWORD_KEY);
            return CryptoJS.AES.encrypt(beforeVal, key, {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
        }
    }
        ;
});